import 'package:azlistview/azlistview.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:changxindianzishangwu/cache/local_cache.dart';
import 'package:changxindianzishangwu/dao/title_dao.dart';
import 'package:changxindianzishangwu/else/lib/common/index.dart';
import 'package:changxindianzishangwu/model/address_book_model.dart';
import 'package:changxindianzishangwu/model/title_user_list_model.dart';
import 'package:changxindianzishangwu/util/colors.dart';
import 'package:changxindianzishangwu/util/fade_router.dart';
import 'package:changxindianzishangwu/util/toast.dart';
import 'package:changxindianzishangwu/util/widget_utils.dart';
import 'package:changxindianzishangwu/widget/get_message_widget.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_slidable/flutter_slidable.dart';
import 'package:get/get.dart';

import 'contacts_titiles_page.dart';

class CreateTitlsPage extends StatefulWidget {
  int type;
  String groupId;
  String groupName;
  CreateTitlsPage({Key key, this.type = 1, this.groupId, this.groupName})
      : super(key: key);

  @override
  _CreateTitlsPageState createState() => _CreateTitlsPageState();
}

class _CreateTitlsPageState extends State<CreateTitlsPage> {
  TextEditingController textEditingController = TextEditingController();
  String groupId;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getData();
  }

  List<AddressBookModel> addressBookList = [];
  List<AddressBookModel> addressBookListCopy = [];
  List<Widget> itemWidget = [];
  TitleUserListModel titleUserList;
  List<String> userId = [];
  getData() async {
    addressBookList = [];
    addressBookListCopy = [];

    if (widget.type != 1) {
      print(widget.groupName + "----------------");
      titleUserList =
          await TitleDao.selectByUserId(widget.groupId, widget.groupName);
      textEditingController.text = titleUserList.data[0].groupName;
      titleUserList.data.forEach((element) {
        if (element.userId == "") {
          addressBookListCopy = [];
        } else {
          addressBookListCopy.add(AddressBookModel(
              name: element.nickName,
              headerUrl: element.avatar,
              userId: element.userId));

          userId.add(element.userId);
        }
      });

      print(userId.toString() + "===========sss");
      addressBookList.addAll(addressBookListCopy);
      SuspensionUtil.setShowSuspensionStatus(addressBookList);
      _handleList(addressBookList);
    }
  }

  void _handleList(List<AddressBookModel> list) {
    if (list.isEmpty) return;
    for (int i = 0, length = list.length; i < length; i++) {
      String pinyin =
          PinyinHelper.getPinyinE(list[i].name == "" ? "没有姓名" : list[i].name);
      String tag = pinyin.substring(0, 1).toUpperCase();
      list[i].namePinyin = pinyin;

      print(list[i]);
      print(list[i].name);
      print(list[i].namePinyin);

      if (RegExp('[A-Z]').hasMatch(tag)) {
        list[i].tagIndex = tag;
      } else {
        list[i].tagIndex = '#';
      }
    }
    // A-Z sort.

    SuspensionUtil.sortListBySuspensionTag(list);

    // add hotCityList.
    // addressBookList.insertAll(0, _hotCityList);

    // show sus tag.
    SuspensionUtil.setShowSuspensionStatus(list);

    setState(() {});
  }

  Future<bool> updateGroup() async {
    if (widget.groupName != textEditingController.text) {
      if (textEditingController.text == '' ||
          textEditingController.text.trim() == '') {
        showToast("标签不能为空");
        return false;
      } else {
        TitleDao.updateGroupName(widget.groupId, textEditingController.text);
        return true;
      }
    } else {
      return true;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        leading: IconButton(
          icon: Text(
            "取消",
            style: TextStyle(fontSize: 16.sp),
          ),
          onPressed: () async {
            if (widget.type == 1 || widget.type == 2) {
              if (groupId != null && groupId != "") {
                var result = await TitleDao.deleteTitle(groupId);
              }
            }

            Navigator.pushAndRemoveUntil(
                context, FadeRoute(ContactsTitilesPage()), (route) => false);
          },
        ),
        elevation: 0,
        title: Text(
          "设置备标签",
          style: TextStyle(
            fontSize: ScreenUtil().setSp(16),
          ),
        ),
        centerTitle: true,
        actions: [
          InkWell(
            onTap: () async {
              if (widget.type == 1) {
                if (textEditingController.text == "" ||
                    textEditingController.text.trim() == '') {
                  showToast("请先输入标签名!");
                } else {
                  groupId = await TitleDao.createTitle(
                      textEditingController.text, int.parse(getUserId()));
                  Navigator.pushAndRemoveUntil(context,
                      FadeRoute(ContactsTitilesPage()), (route) => false);
                }
              } else {
                bool flag = await updateGroup();
                if (flag) {
                  Navigator.pushAndRemoveUntil(context,
                      FadeRoute(ContactsTitilesPage()), (route) => false);
                }
              }
            },
            child: Container(
              alignment: Alignment.center,
              margin: EdgeInsets.only(top: 11, bottom: 11, right: 15),
              height: 10,
              width: ScreenUtil().setWidth(60),
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(6),
                color: Color.fromRGBO(0, 220, 169, 1),
              ),
              child: Text(
                "完成",
                style: TextStyle(
                    color: Colors.white, fontSize: ScreenUtil().setSp(14)),
              ),
            ),
          )
        ],
      ),
      body: Container(
        child: Column(
          children: [
            Container(
              color: Colors.white,
              alignment: Alignment.centerLeft,
              padding: EdgeInsets.only(left: 15.w),
              child: Text(
                "标签名字",
                style: TextStyle(
                    fontSize: 12.sp, color: ZdColor.rgba(193, 193, 193, 1)),
              ),
            ),
            Container(
              height: 60,
              color: Colors.white,
              alignment: Alignment.centerLeft,
              padding: EdgeInsets.only(left: 15.w),
              child: TextField(
                controller: textEditingController,
                onChanged: (value) {
                  print(value);
                },
                keyboardType: TextInputType.name,
                style: TextStyle(fontSize: 15.sp),
                cursorColor: Colors.greenAccent,
                decoration: InputDecoration(
                  hintText: "请设置标签名字",
                  hintStyle: TextStyle(
                      fontSize: 14.sp, color: ZdColor.rgba(193, 193, 193, 1)),
                  border: InputBorder.none,
                ),
              ),
            ),
            SizedBox(
              height: 10,
            ),
            Container(
              color: Colors.white,
              alignment: Alignment.centerLeft,
              padding: EdgeInsets.only(left: 15.w, top: 8),
              child: Text(
                "标签成员",
                style: TextStyle(
                    fontSize: 12.sp, color: ZdColor.rgba(193, 193, 193, 1)),
              ),
            ),
            Container(
              height: 60,
              color: Colors.white,
              alignment: Alignment.centerLeft,
              padding: EdgeInsets.only(left: 15.w),
              child: TextField(
                onTap: () async {
                  if (textEditingController.text == "" ||
                      textEditingController.text.trim() == '') {
                    showToast("请先输入标签名!");
                  } else {
                    if (widget.type == 1) {
                      groupId = await TitleDao.createTitle(
                          textEditingController.text, int.parse(getUserId()));
                      if (groupId == 'error') {
                      } else {
                        Get.to(() => GetMessageWidget(
                            type: 2,
                            groupId: groupId,
                            groupName: textEditingController.text,
                            userList: userId));
                      }
                    } else {
                      bool flag = await updateGroup();
                      if (flag) {
                        Get.to(() => GetMessageWidget(
                            type: 2,
                            groupId: widget.groupId,
                            groupName: textEditingController.text,
                            userList: userId));
                      }
                    }
                  }
                },
                onChanged: (value) {
                  print(value);
                },
                keyboardType: TextInputType.name,
                style: TextStyle(fontSize: 15.sp),
                cursorColor: Colors.greenAccent,
                readOnly: true,
                decoration: InputDecoration(
                  icon: Icon(
                    Icons.add_circle_outline,
                    color: ZdColor.rgba(0, 220, 169, 1),
                  ),
                  hintText: "添加成员",
                  hintStyle: TextStyle(
                      fontSize: 14.sp, color: ZdColor.rgba(0, 220, 169, 1)),
                  border: InputBorder.none,
                ),
              ),
            ),
            Expanded(
              child: AzListView(
                data: addressBookList,
                itemCount: addressBookList.length,
                itemBuilder: (BuildContext context, int index) {
                  AddressBookModel model = addressBookList[index];
                  print(model.name);

                  return Container(
                    alignment: Alignment.bottomCenter,
                    height: 60,
                    child: Column(
                      children: [
                        Container(
                          height: 56,
                          child: Slidable(
                              actionPane:
                                  SlidableScrollActionPane(), //滑出选项的面板 动画
                              actionExtentRatio: 0.25,
                              closeOnScroll: true,
                              secondaryActions: <Widget>[
                                IconSlideAction(
                                    caption: '删除',
                                    color: Colors.red,
                                    icon: Icons.delete,
                                    closeOnTap: true,
                                    onTap: () async {
                                      userId.remove(model.userId);
                                      await TitleDao.updateTitle(
                                          widget.groupId, userId);
                                      userId = [];
                                      setState(() {
                                        getData();
                                      });
                                    }),
                              ],
                              child: Row(
                                children: <Widget>[
                                  Container(
                                      margin: EdgeInsets.only(left: 8),
                                      height: width(40),
                                      width: width(40),
                                      decoration: BoxDecoration(
                                          borderRadius:
                                              BorderRadius.circular(6),
                                          color: Colors.greenAccent,
                                          image: model.headerUrl == null
                                              ? null
                                              : DecorationImage(
                                                  image:
                                                      CachedNetworkImageProvider(
                                                          model.headerUrl))),
                                      child: ClipRRect(
                                        borderRadius: BorderRadius.circular(6),
                                        child: CachedNetworkImage(
                                          imageUrl: model.headerUrl,
                                          fit: BoxFit.cover,
                                        ),
                                      )),
                                  Container(
                                      margin: EdgeInsets.only(
                                        left: 15,
                                      ),
                                      child: Text(model.name ?? "",
                                          style: TextStyle(fontSize: sp(15)))),
                                ],
                              )),
                        ),
                        Divider(
                          height: 1,
                          indent: width(65),
                          endIndent: width(15),
                        )
                      ],
                    ),
                  );
                  ;
                },
                padding: EdgeInsets.zero,
                susItemBuilder: (BuildContext context, int index) {
                  AddressBookModel model = addressBookList[index];
                  String tag = model.getSuspensionTag();
                  return WidGetUtils.getSusItem(context, tag);
                },
                // indexBarData: ['★', ...kIndexBarData],
                indexBarWidth: 15,
                indexBarMargin: EdgeInsets.only(bottom: 4),
                indexBarHeight: 460,
                indexBarItemHeight: 13,
                indexBarData: [],
              ),
            )
          ],
        ),
      ),
    );
  }
}
